var Game = (function(_super){ 
    Laya.UIConfig.closeDialogOnSide=false;
    var  isValid = Utils.getInstance().isValid;
    function Game(){
         Game.super(this);
         this.init(); 
         //游戏倍数
         var rule =this.set.getChildByName('rule');
         Utils.getInstance().registerButtonEffect(rule,{click:Laya.Handler.create(this,this.onRule,[this],false)})

         //关闭倍数弹窗
         var closerule=this.odd.getChildByName('cancel'); 
         Utils.getInstance().registerButtonEffect(closerule,{click:Laya.Handler.create(this,this.closerule,[this],false)})

         //关闭提示弹窗
         var sure=this.Prompt.getChildByName('sure'); 
         Utils.getInstance().registerButtonEffect(sure,{click:Laya.Handler.create(this,this.sure,[this],false)})

         //返回
         var goback =this.set.getChildByName('goback');
         Utils.getInstance().registerButtonEffect(goback,{click:Laya.Handler.create(this,this.onGoBack,[this],false)})

         //设置
         var set =this.set.getChildByName('set');
         Utils.getInstance().registerButtonEffect(set,{click:Laya.Handler.create(this,this.onSet,[this],false)}) 
 
         //声音开关
         var openmusic=this.set.getChildByName('openmusic');
         Utils.getInstance().registerButtonEffect(openmusic,{click:Laya.Handler.create(this,this.onMusic,[this],false)});
 
         //开始游戏
         var startGameBtn =this.startgame.getChildByName('start'); 
         Utils.getInstance().registerButton(startGameBtn,{ normal:"bao/start.png", pressed:"bao/onstart.png", click:Laya.Handler.create(this,this.onStartGame,[this],false)});
          
          //得到赢的积分
         var getmoneyBtn =this.startgame.getChildByName('getmoney'); 
         Utils.getInstance().registerButton(getmoneyBtn,{ normal:"bao/getmoney.png", pressed:"bao/ongetmoney.png", click:Laya.Handler.create(this,this.onGetMoney,[this],false)});
          
        //下注监听
        for (var index = 1; index <= 8; index++) {
             var btn =this["bet{0}".format(index)].getChildByName('bet{0}'.format(index)); 
             Utils.getInstance().registerButton(btn,{normal:"bao/bet{0}.png".format(index),pressed:"bao/onbet{0}.png".format(index),click:Laya.Handler.create(this,this.toBet,[index],false)})
        }
        
        //下注颜色
        var betredBtn=this.betred.getChildByName('betred');
        Utils.getInstance().registerButton(betredBtn,{normal:"bao/red.png",pressed:"bao/onred.png",click:Laya.Handler.create(this,this.toBetred,null,false)})

        //下注颜色
        var betyellowBtn=this.betyellow.getChildByName('betyellow');
        Utils.getInstance().registerButton(betyellowBtn,{normal:"bao/yellow.png",pressed:"bao/onyellow.png",click:Laya.Handler.create(this,this.toBetyellow,null,false)})

        //清除下注
        var clearBtn =  this.clearbet.getChildByName('clear');
        Utils.getInstance().registerButton(clearBtn,{normal:"bao/clean.png",pressed:"bao/onclean.png",click:Laya.Handler.create(this,this.onClearBet,null,false)})


       
    }

    Laya.class(Game,"Game",_super);
    var ben = Game.prototype;
 
    //设置分数
    ben.setScore = function(score,clips){
        var numStr = score.toString();
        var len = numStr.length - 1;
        for (var index = clips.length - 1; index >= 0; index--) {
            var clip = clips[index]; 
            if (len >= 0 ){
                clip.visible = true;
                var num  = numStr.charAt(len); 
                clip.index = this.clipIndex[num];
                len -= 1;
            }else{
                clip.index = this.clipIndex[0];
                clip.visible = false;
            } 
        } 
    }


    //初始化
    ben.init = function(){
        this.count = 0;    //转了几圈
        this.starNum = 0 ; //开始位置
        this.endNum = 0 ;  //结束位置 
        this.index = 0;
        this.lock = false; //锁
        this.isOpenMusic = false; //开启音乐
        this.MAXBET = 99; //最大下注
        this.TOBET =false;//没下注
        this.IPlayer = {   //玩家数据结构
            credit:1000000,
            win:0,
        }
        this.playerCredit = this.IPlayer.credit //保留一份总分副本
        this.openHistory = ["bao/result11.png","bao/result11.png","bao/result11.png","bao/result11.png","bao/result11.png","bao/result11.png","bao/result11.png","bao/result11.png"] //开奖历史
        this.clipIndex = {  //数字转换下标
            0 : 0,
            1 : 9,
            2 : 1,
            3 : 2,
            4 : 8,             
            5 : 3,            
            6 : 4,            
            7 : 5,         
            8 : 6,            
            9 : 7,
        }
 
         //初始化转盘内容  给格子绑定数据
         var maxGrid = 23;  //格子数
         this.gridArray = [] ; //格子数据
         var seq = 1;
         for (var index = 0; index <= maxGrid; index++) {
             var grid = this.opencar.getChildByName("open"+index);
             grid.color = seq%2==0 ? "yellow":"red";
             var config = Config.getInstance().getCarConfig(index)
             grid.config = config;
             //console.log(grid.color,"index",index,config.name)
             var light = grid.getChildByName("show"+index); 
             this.gridArray[index] = {grid:grid,light:light}
             seq += 1;
         }

        //下注倍率绑定 
        for (var index = 1; index <= 8; index++) { 
            var btn =this["bet{0}".format(index)].getChildByName('bet{0}mon'.format(index)); 
            var config = Config.getInstance().getBetConfig(index);
            btn.config = config;
            btn.betCount = 0;

         /**
          var redlight =this["bet{0}".format(index)].getChildByName('show{0}'.format(index));  
          if (redlight)
          redlight.visible = true; */
        }

        this.betred.getChildByName('betmoney').betCount = 0 ;  
        this.betyellow.getChildByName('betmoney').betCount = 0;   
  
         //初始化获得总分clip数组
         this.winScoreArray =[];
         for (var index = 0; index <= 9; index++) { 
            this.winScoreArray[index] = this.winallmoney.getChildByName("item{0}".format(index));
         }

         //初始化自己总分clip数组
         this.myMoneyArray =[];
         for (var index = 0; index <= 9; index++) { 
            this.myMoneyArray[index] = this.mymoney.getChildByName("item{0}".format(index));
         }
          
         this.onBetRestore(); 
         this.setScore(this.IPlayer.credit,this.myMoneyArray);
         this.setScore(0,this.winScoreArray);


         this.openResultHistory();
    }

    //玩家下注押分 
    ben.setBetScore = function(){

        this.playerCredit -= 100; 
        if (this.playerCredit <= 0 ){
            return true
        } 
        this.setScore(this.playerCredit,this.myMoneyArray)

        return  false;
    }
  
    //开始转灯
    ben.runLight = function(num){ 
        this.index = this.index + 1;
        var speen = 0 //速度
        var delay = 0  //延迟
        if (this.gridArray[num] === null || this.gridArray[num] === undefined){
            num = 0; 
        }

        if (this.index / 24 >=1 ){
            speen = 0 +  Math.floor(this.index / 23) * 100
        }
 
        var grid = this.gridArray[num]
        var light = grid.light
        light.visible = true;
        //结束
        if (this.index >= 48 && num == this.endNum){ 
            light.alpha = 1 ;
            this.count = 0 ;
            this.starNum = num; 
            num = 0;
            this.index = 0;
            this.openReward();
            return;
        }
        Laya.Tween.to(light,{alpha:1},speen,Laya.Ease.bounceOut,Laya.Handler.create(this,function(scope,light){
            light.alpha = 0; 
            scope.runLight(num+1)
        },[this,light]),delay);
      }
   
      //关闭倍数
       ben.closerule=function(){
           this.odd.visible=false;
           this.odd.close()
       }
 
      //关闭提示
       ben.sure=function(){
           this.Prompt.visible=false;
           this.Prompt.close()
       }
      //按下开始游戏
      ben.onStartGame=function(){ 
          //提示先下注
          if(this.TOBET != true){
           this.Prompt.visible=true;
           var content=this.Prompt.getChildByName("content");
           content.text="请先下注!"
           this.Prompt.popup();
           return false;
        }
        if (this.lock) return; 
        this.endNum = this.getRandom(0,23); 
        console.log("随机数",this.endNum)
        this.lock = true
        this.runLight(this.starNum)
         
      }
 
      //获取随机数
      ben.getRandom = function(min, max){
        var r = Math.random() * (max - min);
        var re = Math.round(r + min);
        re = Math.max(Math.min(re, max), min) 
        return re;
      }
        
      //开奖结果
      ben.openReward = function(){
            var obj = this.gridArray[this.endNum];
            var config = obj.grid.config;
            //拿到下注车押分 
            var totalCount = 0;
            for (var index = 1; index <= 8; index++) {
                var btn =this["bet{0}".format(index)].getChildByName('bet{0}mon'.format(index));   
                if (btn.config  && btn.config.typ ===  config.typ){
                    var rate  = btn.config.rate ;
                    var betCount =  btn.betCount; 
                    totalCount = rate*betCount*100;
                    break
                } 
            } 
            //颜色分
            var color = obj.grid.color
            var colorScore = 0;
            // "yellow":"red"
            if ("red" === color){ 
                colorScore =  this.betred.getChildByName('betmoney').betCount * 200; 
            }
            if("yellow" === color){
                colorScore =  this.betyellow.getChildByName('betmoney').betCount * 200 ;
            } 
            totalCount += colorScore;
           
            console.log("开奖结果",config.name)
            console.log("totalCount",totalCount);
 
            this.setScore(totalCount,this.winScoreArray)

            //入库历史记录只保持8个记录
            var res = Config.getInstance().getCarResConfig(config.typ)  
            if(this.openHistory.length>=8){
            this.openHistory.shift()
            }
            //this.openHistory.x +=80;
            this.openHistory.push(res)
            this.updateHistoryList();

            //没有中奖
            if(totalCount<=0){
                Laya.timer.once(3000,this,function(){

                        return false;
                })
            }
            this.totalCount = totalCount;
            this.startgame.getChildByName('start').visible=false;
            this.startgame.getChildByName('getmoney').visible=true;
            var musictype=Math.ceil(Math.random()*12);
            if (this.musicPath)
                Laya.SoundManager.stopSound(this.musicPath)
            this.musicPath = "res/music/"+musictype+".mp3";
            Laya.SoundManager.playSound( this.musicPath ); 
            
      }
      //赚取积分
      ben.onGetMoney=function(){
            
            //赢的分 点击得分过渡到 自己总分动画
            var totalCount  = this.totalCount 
            Laya.timer.frameLoop(1,this,function(){  
                 if (totalCount <= 0) {
                    Laya.timer.clearAll(this) 
                    //加总分
                    this.IPlayer.credit = this.playerCredit;  
                    //解锁
                    this.lock = false;
                    //清理下注 
                    this.onClearBet(); 
                    //清0
                    this.totalCount = 0; 
                    this.startgame.getChildByName('start').visible=true;
                    this.startgame.getChildByName('getmoney').visible=false;
                    //这里应该换成 上分的音效
                    Laya.SoundManager.stopSound( "res/music/.mp3");
                    return;
                 }
                 totalCount -= 100;
                 this.setScore(totalCount,this.winScoreArray)
                 this.playerCredit += 100;
                 this.setScore(this.playerCredit,this.myMoneyArray)
            }) 
            
      }
      //最下面一排的下注 位置代表下注的东西
      ben.toBet=function(index){
          console.log("当前点击位置",index)
          var btn =this["bet{0}".format(index)].getChildByName('bet{0}mon'.format(index));  
          Laya.SoundManager.playSound("res/music/8927.wav"); 
          this.upScore(btn);
      }
 
      //上分 99以内的
      ben.upScore = function(btn){ 
          if (this.lock) return console.log("正在开奖,不能押注")
          if (this.setBetScore()) return console.log("没分了");

          var clip1  = btn.getChildByName("item0")//.autoPlay = true
          var clip2  = btn.getChildByName("item1")//.autoPlay = true 
          if(btn.betCount >= this.MAXBET) 
             return console.log("超过上限了!!!!")
          
          btn.betCount += 1;
          var score = btn.betCount;
          var numStr = score.toString();
          var tenStr = null
          var aStr = null

          this.TOBET = true; //下注
          if (score >= 10){
             tenStr = numStr.charAt(0)
             aStr = numStr.charAt(1)
             clip1.index = this.clipIndex[tenStr];
             clip2.index = this.clipIndex[aStr];
          }else{
             aStr = numStr.charAt(0) 
             clip1.index = this.clipIndex[0];
             clip2.index = this.clipIndex[aStr]
          } 
          
      }
 
      //下注红色
      ben.toBetred=function(){
        console.log("下注红色")
        var btn =this.betred.getChildByName('betmoney');  
        Laya.SoundManager.playSound("res/music/8927.wav"); 
        this.upScore(btn); 
      }
      //下注黄色
      ben.toBetyellow=function(){
          console.log("下注黄色") 
          var btn =this.betyellow.getChildByName('betmoney');   
          Laya.SoundManager.playSound("res/music/8927.wav"); 
          this.upScore(btn); 
      }
      //清除所有上分
      ben.onClearBet=function(){
        console.log("清除下注") 
        if (this.lock) return console.log("正在开奖,不能清除押注")
        this.TOBET = false;
        this.onBetRestore();
        //恢复积分
        this.playerCredit = this.IPlayer.credit;
        this.setScore(this.playerCredit,this.myMoneyArray)
      }
      //设置
      ben.onSet=function(){
            console.log("设置")
      } 
      //返回
      ben.onGoBack=function(){
            console.log("返回")
      }
      //开启规则弹窗
      ben.onRule=function(){
           this.odd.visible=true;
           this.odd.popup()
      }
     // 声音设置
     ben.onMusic=function(){
         var openmusic=this.set.getChildByName('openmusic');
         this.isOpenMusic = !this.isOpenMusic
        if (this.isOpenMusic){
            console.log("关闭音乐")
            openmusic.skin = "bao/closemusic.png"
        }else{
            console.log("开启音乐")
            openmusic.skin = "bao/openmusic.png"
        }
     }

     //下注复原
     ben.onBetRestore = function(){
         //下注监听
        for (var index = 1; index <= 8; index++) {  
          var btn =this["bet{0}".format(index)].getChildByName('bet{0}mon'.format(index));  
          var clip1  = btn.getChildByName("item0")
          var clip2  = btn.getChildByName("item1")
          btn.betCount = 0;
          clip1.index = clip2.index = this.clipIndex[0];
        }
        //红黄下注
        var btn = this.betred.getChildByName('betmoney') 
        var clip1  = btn.getChildByName("item0")
        var clip2  = btn.getChildByName("item1")
        btn.betCount = 0;
        clip1.index = clip2.index = this.clipIndex[0];

        var btn = this.betyellow.getChildByName('betmoney');  
        var clip1  = btn.getChildByName("item0")
        var clip2  = btn.getChildByName("item1")
        btn.betCount = 0;
        clip1.index = clip2.index = this.clipIndex[0];
         
     }

     //开奖历史
     ben.openResultHistory = function(){
        var list = this.resulthistory
        list.itemRender = Laya.Image 
        list.repeatX = 8;
        list.repeatY = 0;
        list.spaceX = 5;  
        list.array = this.openHistory;
        list.vScrollBarSkin = " "; 
        list.renderHandler = new Laya.Handler(this, this.updateItem);  
     }

     ben.updateItem = function(cell, index) { 
        var res = cell.dataSource; 
        cell.skin = res;
        cell.size(73,73)
    }

     //更新开奖历史
     ben.updateHistoryList = function(){
        var list = this.resulthistory  
        list.array = this.openHistory
        list.refresh();
     }

    return Game;
})(ui.GameUI);